import { defineStore } from 'pinia';

interface CompanyType {
  id: number | null;
  name: string;
  create_user: number | null;
  projects: any[];
  status: '待签约' | '已签约' | '合约中' | '合约到期';
  style: number | null;
  host: string;
  [key: string]: any;
}
export const useIuserCompanyStore = defineStore('iuserCompany', {
  state: (): CompanyType => ({
    id: null,
    name: '',
    create_user: null,
    projects: [],
    status: '待签约',
    style: null,
    host: '',
  }),
  getters: {
    
  },
  actions: {
    setCompanyDetail(msg: Partial<CompanyType>): void {
      for (const key in this) {
        if (Object.prototype.hasOwnProperty.call(msg, key)) {
          this[key] = msg[key]!;
        }
      }
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

interface RolesType {
  id: number;
  name: string;
  parent_id: null | number;
  company_id: number;
  project_id: null | number;
  [key: string]: any;
}
interface IuserInfoType {
  admin_projects2: number[];          //主题2使用，是哪个项目的管理员---在项目的admin_user设置成了该用户，
  company_functions: string[];        //公司权限
  company_roles: RolesType[];         //公司角色
  created_company: number | null;     //不为null 则是超管
  info: {
    company: number | null;           //此人所在的公司id
    company_logo: string;             //此人所在的公司logo
    company_name: string;             //此人所在的公司名称
    company_superuser: number | null; //公司的超管id
    contract: string;                 //联系方式
    department: {
      addr?: string;                  //所属组织的地址
      code?: string;                  //所属组织的编码
      company?: number;               //所属组织的所属公司
      department?: number;             //所属组织的id
      dtype?: number;                 //所属组织的组织类型
      fzr?: string;                   //所属组织的负责人
      name?: string;                  //所属组织的名称
      parent?: number | null;         //所属组织的上级组织
      phone?: string;                 //所属组织的联系电话
    };
    id: number | null;                //当前用户id
    logout_time: string;              //登出时间
    openid: boolean;                  //有么有公众号吧
    projects: any[];                  //在哪些项目下
    truename: string;                 //真实姓名
    type: '注册用户' | '公司用户' | '项目用户' | '恒济用户' | '合约用户'; //是什么类型用户
    units_flag: string;               //空字符串或'[project_id]'的json数组
  };
  project_functions: {
    [key: number]: string[];          //项目下的权限
  };
  project_roles: RolesType[];         //项目下的权限
  projects: number[];                 //主题1使用，是哪个项目的管理员---在公司角色权限那里此人所在的角色勾了哪些项目,
  style_m: {
    id: number | null;                //移动端主题id
    ifile: string;                    //移动端主题缩略图
    name: string;                     //移动端主题名称
    type: string;                     //类型
  };
  units: number[];                    //拥有哪些站点的权限
  [key: string]: any;                 //未知属性
}
export const useIuserInfoStore = defineStore('iuserInfo', {
  state: (): IuserInfoType => ({
    admin_projects2: [],
    company_functions: [],
    company_roles: [],
    created_company: null,
    info: {
      company: null,
      company_logo: '',
      company_name: '',
      company_superuser: null,
      contract: '',
      department: {},
      id: null,
      logout_time: '',
      openid: false,
      projects: [],
      truename: '',
      type: '项目用户',
      units_flag: '',
    },
    project_functions: {},
    project_roles: [],
    projects: [],
    style_m: {
      id: null,
      ifile: '',
      name: '',
      type: '',
    },
    units: [],
  }),
  getters: {
    getHandleRight: (state) => {
      const currentWatchStore = useCurrentWatchStore();
      const { level, curProject } = currentWatchStore;
      const { company_functions, project_functions, created_company, info, admin_projects2 } = state;
      const isCoSuper = created_company === info.company;
      const isProSuper = !!(curProject.id && admin_projects2.includes(curProject.id));
      return <T extends string>(codes: T[]): Record<T, boolean> => {
        const RIGHT: Record<T, boolean> = {} as Record<T, boolean>;
        if (level === 'company') {
          codes.forEach((code: T) => {
            RIGHT[code] = company_functions.includes(code) || isCoSuper;
          });
        } else if (level === 'project') {
          const cur_project_functions = project_functions[curProject.id as number] || [];
          codes.forEach((code: T) => {
            RIGHT[code] = cur_project_functions.includes(code) || isCoSuper || isProSuper;
          });
        } else {
          codes.forEach((code: T) => {
            RIGHT[code] = false;
          });
        }
        return RIGHT;
      };
    }
  },
  actions: {
    setIuserInfo(msg: Partial<IuserInfoType>): void {
      for (const key in this) {
        if (Object.prototype.hasOwnProperty.call(msg, key)) {
          this[key] = msg[key]!;
        }
      }
    },
  },
  persist: {
    storage: sessionStorage,
  },
});

export interface CurrentMenuType {
  id: number;
  alias: string;
  menu: null | number;
  menu__name?: string;
  menu__path?: string;
  params: string;
  children?: CurrentMenuType[];
  parent: null | 'null' | number;
  roles?: number[];
  type: string;
  type1: string;
  used: boolean;
  icon?: number;
  icon__color?: string;
  icon__file__file?: string;
  [key: string]: any;
}
export interface ProjectDetailType {
  id?: number;
  name?: string;
  params?: string;
  admin_user?: number | null;
  [key: string]: any;
}
interface CurrentWatchType {
  projectList: ProjectDetailType[];
  level: 'company' | 'project' | '';
  curMenus: CurrentMenuType[];         //当前公司或者当前项目拥有的有权限的菜单
  curProject: ProjectDetailType;
}
export const useCurrentWatchStore = defineStore('currentWatch', {
  state: (): CurrentWatchType => ({
    projectList: [],
    level: '',
    curMenus: [],
    curProject: {
      admin_user: null,
    },
  }),
  getters: {
    getProjectsOfValidMenus: (state): ProjectDetailType[] => {
      const localMenusStore = useLocalMenusStore();
      const proListsMenu = localMenusStore.getProListsMenuOfPC;
      const validIds = proListsMenu.map(i => i.project);
      return state.projectList.filter(i => i.id && validIds.includes(i.id));
    }
    // getCurrentID: (state) => {
    //   return state.menus.reduce((menuID: any, items: any) => {
    //     return menuID;
    //   }, null);
    // },
  },
  actions: {
    setProjectAdmin(projectID: number, iuser: number, truename: string): void {
      const project = this.projectList.find(i => i.id === projectID);
      if (project) {
        project.admin_user = iuser;
        project.admin_user_truename = truename;
      }
    },
    setProjectList(arrs: ProjectDetailType[]): void {
      this.projectList = arrs;
    },
    setLevel(level: 'company' | 'project' | ''): void {
      this.level = level;
    },
    setCurMenus(curMenus: CurrentMenuType[]): void {
      this.curMenus = curMenus;
    },
    setCurProject(curProject: ProjectDetailType): void {
      this.curProject = curProject;
    },
  },
  persist: {
    storage: sessionStorage,
  }
});

interface LocalStorageType {
  menuCollapse: boolean;
}
export const useLocalStorage = defineStore('localStorage', {
  state: (): LocalStorageType => ({
    menuCollapse: false,
  }),
  getters: {
    
  },
  actions: {
    setMenuCollapse(menuCollapse: boolean): void {
      this.menuCollapse = menuCollapse;
    },
  },
  persist: {
    storage: localStorage,
  }
});

/* 所有有效菜单，包括移动端 */
interface LocalMenusType {
  CoMenus: CurrentMenuType[];
  ProListsMenu: {
    children: CurrentMenuType[];
    project: number;
  }[];
};
export const useLocalMenusStore = defineStore('localMenus', {
  state: (): LocalMenusType => ({
    CoMenus: [],
    ProListsMenu: [],
  }),
  getters: {
    getCoMenusOfPC: (state) => {
      return state.CoMenus.filter(item => item.type1 === 'PC');
    },
    getValidProjects: (state): number[] => {
      const pMenusNode = state.ProListsMenu.map(node => {
        return { ...node, children: node.children.filter(i => i.type1 === 'PC') }
      }).filter(item => item.children.length);
      return pMenusNode.map(i => i.project);
    },
    getProListsMenuOfPC: (state): typeof state.ProListsMenu => {
      const pMenusNode = state.ProListsMenu.map(node => {
        return { ...node, children: node.children.filter(i => i.type1 === 'PC') }
      }).filter(item => item.children.length);
      return pMenusNode;
    },
    getProjectMenuOfPC: (state): (projectID: number) => { children: CurrentMenuType[]; project: number; } | undefined => {
      const pMenusNode = state.ProListsMenu.map(node => {
        return { ...node, children: node.children.filter(i => i.type1 === 'PC') }
      }).filter(item => item.children.length);
      return (projectID: number) => {
        return pMenusNode?.find(i => i.project === projectID);
      };
    },
  },
  actions: {
    setLocalMenus(msg: Partial<LocalMenusType>): void {
      for (const key in this) {
        if (Object.prototype.hasOwnProperty.call(msg, key)) {
          this[key] = msg[key]!;
        }
      }
    },
  },
  persist: {
    storage: sessionStorage,
  },
});